﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.Dto;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.BasicData.Application
{
    /// <summary>
    /// 生产线服务实现类
    /// 提供生产线的增删改查等业务功能
    /// </summary>
    public class ProductionlineServices : IProductionlineServices
    {
        private readonly IBaseRepository<ProductionlineModel> productionline;
        private readonly IBaseRepository<Workshopmanagementmodel> workshop;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数，通过依赖注入获取仓储和映射器
        /// </summary>
        /// <param name="productionline">生产线仓储接口</param>
        /// <param name="workshop">车间仓储接口</param>
        /// <param name="mapper">AutoMapper映射器</param>
        public ProductionlineServices(
            IBaseRepository<ProductionlineModel> productionline, 
            IBaseRepository<Workshopmanagementmodel> workshop,
            IMapper mapper)
        {
            this.productionline = productionline;
            this.workshop = workshop;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加生产线
        /// </summary>
        /// <param name="model">生产线模型</param>
        /// <returns>添加结果</returns>
        public ApiResult<int> AddProductionline(ProductionlineModel model)
        {
            //添加
            var models = mapper.Map<ProductionlineModel>(model);
            model.Id = YitIdHelper.NextId();
            model.IsDeleted=false;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "添加成功",
                Data = productionline.Add(models),
            };
        }

        /// <summary>
        /// 删除生产线（逻辑删除）
        /// </summary>
        /// <param name="id">生产线ID</param>
        /// <returns>删除结果</returns>
        public ApiResult<int> DeleteProductionline(long id)
        {
            //根据id修改逻辑删除为 true
            var model = productionline.GetValue(x => x.Id == id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = productionline.Update(model),
            };
        }

        /// <summary>
        /// 获取所有未删除的生产线
        /// </summary>
        /// <returns>生产线列表</returns>
        public ApiResult<List<ProductionlineModel>> GetAllProductionline()
        {
           return new ApiResult<List<ProductionlineModel>>()
           {
               Code = ApiEnums.Success,
               Message = "查询成功",
               Data = productionline.GetAll().Where(x => x.IsDeleted == false).ToList()
           };
        }

        /// <summary>
        /// 分页查询生产线，并关联车间信息
        /// </summary>
        /// <param name="productionlinecode">生产线编码（可选）</param>
        /// <param name="Productionlinename">生产线名称（可选）</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">每页大小</param>
        /// <returns>分页结果</returns>
        public ApiPaging<List<ProductionlineDto>> GetProductionline(string? productionlinecode, string? Productionlinename, int pageindex, int pagesize)
        {
            try
            {
                //查询名称来显示数据
                var list = productionline.GetAll().Where(x => x.IsDeleted == false);
                if (productionlinecode != null)
                {
                    list = list.Where(x => x.Productionlinecode.Contains(productionlinecode));
                }
                if (Productionlinename != null)
                {
                    list = list.Where(x => x.Productionlinename.Contains(Productionlinename));
                }
                
                // 获取所有车间信息
                var workshopList = workshop.GetAll().Where(x => x.IsDeleted == false).ToList();
                
                // 使用LINQ查询进行联表查询
                var result = from p in list.ToList()
                             join w in workshopList on p.Workshopid equals w.Id into wGroup
                             from w in wGroup.DefaultIfEmpty()
                             select new ProductionlineDto
                             {
                                 Id = p.Id,
                                 Productionlinecode = p.Productionlinecode,
                                 Productionlinename = p.Productionlinename,
                                 Workshopid = p.Workshopid,
                                 Workshopname = w != null ? w.Workshopname : "",
                                 Productionlinedescription = p.Productionlinedescription,
                                 Productionlineattributes = p.Productionlineattributes,
                                 CreatedBy = p.CreatedBy,
                                 CreatedTime = p.CreatedTime,
                                 UpdatedBy = p.UpdatedBy,
                                 UpdatedTime = p.UpdatedTime,
                                 IsDeleted = p.IsDeleted
                             };

                var resultList = result.ToList();
                
                // 实现分页操作
                return new ApiPaging<List<ProductionlineDto>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = resultList.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(),
                    TotalCount = resultList.Count
                };
            }
            catch (Exception ex)
            {
                return new ApiPaging<List<ProductionlineDto>>()
                {
                    Code = ApiEnums.Fail,
                    Message = "查询失败：" + ex.Message,
                    Data = new List<ProductionlineDto>(),
                    TotalCount = 0
                };
            }
        }
       /// <summary>
       /// 根据id查询
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       /// <exception cref="NotImplementedException"></exception>
        public ApiResult<ProductionlineModel> GetProductionlineById(long id)
        {
           // 根据id查询
           var model = productionline.GetValue(x => x.Id == id);
            return new ApiResult<ProductionlineModel>()
            {
                Code = ApiEnums.Success,
                Message = "查询成功",
                Data = model
            };
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> UpdateProductionline(ProductionlineModel model)
        {
            //查询获取id判断是否有这条数据从而修改
            var query = productionline.GetValue(x => x.Id == model.Id);
            //保存创建人添加修改人和修改时间
            model.UpdatedBy = "admin";
            model.UpdatedTime = DateTime.Now;
            if (query == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "没有此数据"
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "修改成功",
                Data = productionline.Update(model)
            };
        }
    }
}
